package com.arcvideo.acsplayer.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.RejectedExecutionException;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.arcvideo.acsplayer.R;
import com.arcvideo.acsplayer.app.AcsPlayerApplication;
import com.arcvideo.acsplayer.config.ApplicationConfig;
import com.arcvideo.acsplayer.dialog.ProgressDialog;
import com.arcvideo.acsplayer.httprequest.BaseHttpRequest;
import com.arcvideo.acsplayer.httprequest.BaseHttpRequest.HttpRequestCallback;
import com.arcvideo.acsplayer.httprequest.VideoRequest;
import com.arcvideo.acsplayer.mode.ArclouldVideoInfo;
import com.arcvideo.acsplayer.mode.ArclouldVideoList;
import com.arcvideo.acsplayer.mode.ArclouldVideoListLocal;
import com.arcvideo.acsplayer.mode.TranscodedVideoInfo;
import com.arcvideo.acsplayer.utils.DateUtil;
import com.arcvideo.acsplayer.utils.EncryptUtil;
import com.arcvideo.acsplayer.utils.ErrorUtil;
import com.arcvideo.acsplayer.utils.JsonUtil;
import com.arcvideo.acsplayer.utils.NetUtil;
import com.arcvideo.acsplayer.widget.HDselectView;

public class LoadArclouldActivity extends BaseActivity implements OnClickListener, OnItemClickListener {
	private TextView mTitleText = null;
	private ImageButton mBackButton = null;
	private ProgressDialog mLoadingDialog = null;
	private ListView mVideoFileListView = null;
	private ArrayList<ArclouldVideoInfo> mVideoList = null;
	private ArclouldVideoList mArclouldVideoList = null;
	private ArclouldVideoListLocal mArclouldVideoListLocal = null;
	private VideoAdapter mVideoAdapter = null;
	private String mId = "1";
	private int mCurrentPosition = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_load_clould_file);
		initUi();
		initData();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.id_title_left_btn :
				finish();
				break;
			default :
				break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
		mCurrentPosition = position;
		// toArclouldChildListActivity();
		toPlayActivity();
	}

	/**
	 * 初始化UI
	 */
	private void initUi() {
		mTitleText = (TextView) findViewById(R.id.id_title_text_view);
		mTitleText.setText(R.string.select_video_from_clould);

		mBackButton = (ImageButton) findViewById(R.id.id_title_left_btn);
		mBackButton.setOnClickListener(this);

		mVideoFileListView = (ListView) findViewById(R.id.list);
		mVideoFileListView.setOnItemClickListener(this);

		mLoadingDialog = ProgressDialog.createDialog(this);
		mLoadingDialog.setMessage(getString(R.string.buffering));
		mLoadingDialog.hide();
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		initLocalData();
		initArcloudData();
	}

	/**
	 * 初始化本地数据
	 */
	private void initLocalData() {
		String videoListString = JsonUtil.getJsonStringFromFile(getBaseContext(), "localplaylist.json");
		if (videoListString == null)
			return;

		JSONObject videoList = null;
		try {
			videoList = new JSONObject(videoListString);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		if (videoList == null )
			return;

		mArclouldVideoListLocal = new ArclouldVideoListLocal(videoList);
	}

	/**
	 * 初始化当红云数据
	 */
	private void initArcloudData() {
		// http://api.hongshiyun.net/rest?accessKey=ac92adda-02b&sort=title&order=asc&start=1&action=queryVideo&number=20&signature=d8d1f07b526d7ff8312e2b182f5b368c6584fb7ab3e1cfa7eb9fdb1729246a8a
		try {
			String action = "queryVideo";
			String start = "1";
			String number = "20";
			String sort = "title";
			String order = "asc";
			String signature = "";

			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("accessKey", ApplicationConfig.ACCESSKEY);
			params.put("action", action);
			params.put("start", "1");
			params.put("number", "20");
			params.put("sort", "title");
			params.put("order", "asc");
			signature = EncryptUtil.generateSignature(params, ApplicationConfig.ACCESSSECRT);

			VideoRequest request = new VideoRequest();
			request.setHttpRequestCallback(new HttpRequestCallback() {

				@Override
				public void OnRequestReturn(BaseHttpRequest request, Object data) {
					if (data != null && data instanceof JSONObject) {
						JSONObject object = ((JSONObject) data);
						int code = object.optInt("code");
						if (code == ApplicationConfig.SUCCESS) {
							mArclouldVideoList = new ArclouldVideoList(object);
							if (null != mArclouldVideoList.arclouldVideoList) {
								mVideoList = mArclouldVideoList.arclouldVideoList;

								if (mArclouldVideoListLocal != null && mArclouldVideoListLocal.arclouldVideoListLocal.size() > 0) {
									for (int i = mArclouldVideoListLocal.arclouldVideoListLocal.size() - 1; i >= 0; i--) {
										ArclouldVideoInfo videoInfo = new ArclouldVideoInfo();
										videoInfo.transcodedVideoInfo = new ArrayList<TranscodedVideoInfo>();
										TranscodedVideoInfo transcodedVideoInfo1 = new TranscodedVideoInfo(null);
										transcodedVideoInfo1.hlsUrl =  mArclouldVideoListLocal.arclouldVideoListLocal.get(i).playurl;
										transcodedVideoInfo1.name = HDselectView.STATE_4K;
										videoInfo.transcodedVideoInfo.add(transcodedVideoInfo1);
										TranscodedVideoInfo transcodedVideoInfo2 = new TranscodedVideoInfo(null);
										transcodedVideoInfo2.hlsUrl =  mArclouldVideoListLocal.arclouldVideoListLocal.get(i).playurl;
										transcodedVideoInfo2.name = HDselectView.STATE_ULTRA_CLEAR;
										videoInfo.transcodedVideoInfo.add(transcodedVideoInfo2);
										TranscodedVideoInfo transcodedVideoInfo3 = new TranscodedVideoInfo(null);
										transcodedVideoInfo3.hlsUrl =  mArclouldVideoListLocal.arclouldVideoListLocal.get(i).playurl;
										transcodedVideoInfo3.name = HDselectView.STATE_HD;
										videoInfo.transcodedVideoInfo.add(transcodedVideoInfo3);
										TranscodedVideoInfo transcodedVideoInfo4 = new TranscodedVideoInfo(null);
										transcodedVideoInfo4.hlsUrl =  mArclouldVideoListLocal.arclouldVideoListLocal.get(i).playurl;
										transcodedVideoInfo4.name = HDselectView.STATE_SD;
										videoInfo.transcodedVideoInfo.add(transcodedVideoInfo4);
										TranscodedVideoInfo transcodedVideoInfo5 = new TranscodedVideoInfo(null);
										transcodedVideoInfo5.hlsUrl =  mArclouldVideoListLocal.arclouldVideoListLocal.get(i).playurl;
										transcodedVideoInfo5.name = HDselectView.STATE_SMOOTH;
										videoInfo.transcodedVideoInfo.add(transcodedVideoInfo5);
										videoInfo.title = mArclouldVideoListLocal.arclouldVideoListLocal.get(i).title;
										videoInfo.thumbnail = mArclouldVideoListLocal.arclouldVideoListLocal.get(i).thumbnialurl;
										videoInfo.type = mArclouldVideoListLocal.arclouldVideoListLocal.get(i).playtype;
										mVideoList.add(0, videoInfo);
									}
								}

								mVideoAdapter = new VideoAdapter(getApplicationContext(), mVideoList);
								mVideoFileListView.setAdapter(mVideoAdapter);
							}
						} else {
							ErrorUtil.showToast(getApplicationContext(), code, R.string.data_error);
						}
						mLoadingDialog.hide();
					}
				}
			});
			request.executeOnPoolExecutor(action, start, number, sort, order, signature);
		} catch (RejectedExecutionException e1) {
			e1.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		mLoadingDialog.show();

		if (!NetUtil.isNetworkAvailable(this)) {
			ShowRemandDialog(R.string.remind, R.string.net_error_info3);
			mLoadingDialog.hide();
		}
	}


	/**
	 * 进入子列表页面
	 */
	private void toArclouldChildListActivity() {
		Intent displayIntent = new Intent(LoadArclouldActivity.this, LoadArclouldChildListActivity.class);
		displayIntent.putExtra("ID", mId);
		startActivity(displayIntent);
	}

	/**
	 * 进入播放页面
	 */
	private void toPlayActivity() {
		Intent displayIntent = new Intent(LoadArclouldActivity.this, PlayActivity.class);
		displayIntent.putExtra(PlayActivity.URLTYPE, PlayActivity.FROM_ARCLOULD);
		displayIntent.putExtra(PlayActivity.URLDATA, mVideoList);
		displayIntent.putExtra(PlayActivity.URLINDEX, mCurrentPosition);
		startActivity(displayIntent);
	}

	/**
	 * 视频列表
	 *
	 * @author skl5250
	 *
	 */
	public class VideoAdapter extends BaseAdapter {
		/**
		 * 视频信息
		 */
		private ArrayList<ArclouldVideoInfo> videoList = new ArrayList<ArclouldVideoInfo>();

		/**
		 * 上下文
		 */
		private Context context;

		/**
		 * 构造函数
		 */
		public VideoAdapter(Context context, ArrayList<ArclouldVideoInfo> videoList) {
			this.context = context;
			this.videoList = videoList;
		}

		/**
		 * 更新列表
		 */
		public void updateList(ArrayList<ArclouldVideoInfo> videoList) {
			this.videoList = videoList;
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return this.videoList.size();
		}

		@Override
		public Object getItem(int position) {
			return this.videoList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@SuppressLint("NewApi")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			final ArclouldVideoInfo video = this.videoList.get(position);
			if (convertView == null) {
				viewHolder = new ViewHolder();
				convertView = LayoutInflater.from(context).inflate(R.layout.item_local, null);
				viewHolder.video_thume = (ImageView) convertView.findViewById(R.id.left_img);
				viewHolder.video_title = (TextView) convertView.findViewById(R.id.video_title);
				//viewHolder.video_time = (TextView) convertView.findViewById(R.id.video_time);

				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			viewHolder.video_title.setText(video.title);
			AcsPlayerApplication.getInstance().getImageLoader().displayImage(video.thumbnail, viewHolder.video_thume);
			//viewHolder.video_time.setText(DateUtil.getTimeCount(video.duration));
			return convertView;
		}

		private class ViewHolder {
			ImageView video_thume;
			TextView video_time;
			TextView video_title;
		}
	}

}